<template>
  <div class="container">
    <div class="header">
      <van-icon name="arrow-left" @click="goBack" class="img" />
      <p class="strong" v-if="baseState && baseState?.nick">{{ baseState.nick }}</p>
      <p @click="onConfigClick('threeCar')">3D看车</p>
    </div>
    <div class="content">
      <div class="content_top">
        <div class="image" v-if="image.length === 36">
          <div class="image_in" v-for="(item, index) in image" :key="index">
            <img :src="item" v-show="flag == index ? (opacity = 1) : (opacity = 0)" />
          </div>
        </div>
        <div class="image" v-else>
          <div class="image_in">
            <img :src="image" />
          </div>
        </div>
        <div v-show="photoCount > 1" class="iconIndex">
          <span v-for="(item, index) in images" :key="index" class="radius" :style="{ background: item.color }"
            @click="color_change(index)"></span>
        </div>
        <div class="right" @click="onConfigClick">
          <p>外观</p>
          <p>图片</p>
          <p>内饰</p>
        </div>
      </div>
      <div class="content_bottom">
        <p>
          <span class="left">{{ baseState.nick }}</span><span>&nbsp;&nbsp;紧凑型车/排量1.0T 1.5T</span>
        </p>
        <p>
          <span class="left">{{ baseState.dealer_price }}</span><span>&nbsp;&nbsp;{{ baseState.series_clue_count
          }}></span>
        </p>
      </div>
    </div>
    <div class="footer">
      <van-tabs v-model:active="active" background="linear-gradient(30deg, #ddd, #eee, #fff, #eee)">
        <van-tab title="在售">
          <div class="lineCar" v-if="onlineCar.length > 0">
            <CarList :lineCar="lineCar" v-for="lineCar in onlineCar" :key="lineCar.info.id" />
          </div>
          <div class="lineCar emtyp" v-else>
            <p>暂无数据~</p>
          </div>
        </van-tab>
        <van-tab title="停售">
          <div class="lineCar" v-if="offlineCar.length > 0">
            <CarList :lineCar="lineCar" v-for="lineCar in offlineCar" :key="lineCar.info.id" />
          </div>
          <div class="lineCar emtyp" v-else>
            <p>暂无数据~</p>
          </div>
        </van-tab>
        <van-tab title="同级">
          <SameCar :sameCar="sameLevelCars" @refreshCar="refreshCar" v-if="sameLevelCars" />
          <div class="emtyp" v-else>
            <p>暂无数据~</p>
          </div>
        </van-tab>
      </van-tabs>
    </div>
  </div>
</template>

<script>
import {
  nextTick,
  onBeforeMount,
  onBeforeUnmount,
  reactive,
  toRefs,
} from "vue";
import { useRoute, useRouter } from "vue-router";
import { get } from "@/tool/get";
import CarList from "@/components/carList.vue";
import SameCar from "@/components/sameCar.vue";
import { Toast } from "vant";
export default {
  name: "carItems",
  setup() {
    const route = useRoute();
    const router = useRouter();
    const goBack = () => {
      router.back(-1);
    };
    const getCarsPicture = async (id) => {
      await get("/data/getCarsPicture", { params: id }).then((res) => {
        state.threePictureList = res.data.data.category_list.filter(
          (p) => p.text === "内饰"
        )[0]?.vr_image;
        state.threePictureList
          ? (state.threePictureList = state.threePictureList.map((p) => {
            p.vr_list = {
              front_vr: p.vr_list[0].front_vr,
              rear_vr: p.vr_list[0].rear_vr,
            };
            return p;
          }))
          : null;
        state.image =
          res.data.data.series_entrance_info.cover_url ||
          res.data.data.category_list[0]?.color_pic_list[0].pics;
        if (res.data.data.category_list[0]?.color_pic_list.length > 0) {
          state.image = res.data.data.category_list[0].color_pic_list[0].pics;
          state.images = res.data.data.category_list[0].color_pic_list;
          state.photoCount = res.data.data.category_list[0].color_pic_list.length;
        } else {
          state.image = res.data.data.series_entrance_info.cover_url;
        }
      });
    };
    const getCarDetail = async (id) => {
      await get("/data/carDetail", { params: id }).then((res) => {
        res = res.data.data
        state.baseState.nick = res.baseState.nick;
        state.baseState.dealer_price = res.baseState.dealer_price;
        state.baseState.series_clue_count = res.baseState.series_clue_count;
        state.sameLevelCars = res.sameLevelCars;
      });
    };
    const getOnOrOffCarDetail = async (id) => {
      get("/data/_carDetail", { params: id }).then((res) => {
        res = res.data.data
        state.offlineCar = res.offline
        state.onlineCar = res.online
      });
    };
    onBeforeMount(async () => {
      await getCarsPicture(route.params.id);
      await getCarDetail(route.params.id);
      await getOnOrOffCarDetail(route.params.id);
      if (state.onlineCar) {
        Toast.clear();
      } else {
        Toast.fail("数据加载失败");
      }
    });
    const refreshCar = async (id) => {
      if(id === Number(route.params.id)) {
        Toast.success('已经是该车了')
        return 
      } 
      let toast = Toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });
      await getCarsPicture(id);
      await getCarDetail(id);
      await getOnOrOffCarDetail(id);
      new Promise(async (res) => {
        setTimeout(() => {
          res();
        }, 0);
      }).then(() => toast.clear());
    };
    nextTick(() => {
      document
        .querySelector(".content_top")
        .addEventListener("touchstart", ScrollStart, false);
      document
        .querySelector(".content_top")
        .addEventListener("touchmove", Scroll, false);
      // document
      //   .querySelector(".content_top")
      //   .addEventListener("touchend", ScrollEnd, false);
    });
    onBeforeUnmount(() => {
      document
        .querySelector(".content_top")
        .removeEventListener("touchstart", ScrollStart, false);
      document
        .querySelector(".content_top")
        .removeEventListener("touchmove", Scroll, false);
      // document
      //   .querySelector(".content_top")
      //   .removeEventListener("touchend", ScrollEnd, false);
    });
    const ScrollStart = (e) => {
      state.clientStartX = Math.floor(e.changedTouches[0].clientX);
    };
    const Scroll = (e) => {
      if (
        state.clientStartX - Math.floor(e.changedTouches[0].clientX) > 10
      ) {
        if (state.flag <= 0) {
          state.flag = state.image.length - 1;
        } else {
          state.flag--;
        }
        state.clientStartX = Math.floor(e.changedTouches[0].clientX)
      } else if (
        state.clientStartX - Math.floor(e.changedTouches[0].clientX) < -10
      ) {
        if (state.flag >= state.image.length - 1) {
          state.flag = 0;
        } else {
          state.flag++;
        }
        state.clientStartX = Math.floor(e.changedTouches[0].clientX)
      }
    };
    // const ScrollEnd = () => {

    // };
    const color_change = (index) => {
      let toast = Toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });
      new Promise((res) => {
        state.image = state.images[index].pics
        setTimeout(() => {
          res();
        }, 0);
      }).then(() => toast.clear())
    };
    const onConfigClick = (e) => {
      if (e.target?.innerHTML === "内饰" || e === "threeCar") {
        Toast.loading({
          message: "加载中...",
          forbidClick: true,
          duration: 0,
        });
        router.push({
          name: "threeCar",
          path: "/carDetail/threeCar",
          params: { threeCar: JSON.stringify(state.threePictureList) },
        });
      } else {
        Toast.fail("组件暂未开发");
      }
    };
    const state = reactive({
      flag: 0,
      clientStartX: 0,
      threePictureList: [],
      image: [],
      images: [],
      photoCount: 0,
      baseState: {
        dealer_price: undefined,
        nick: undefined,
        series_clue_count: undefined
      },
      sameLevelCars: [],
      onlineCar: [],
      offlineCar: [],
      active: 0,
    });
    return {
      ...toRefs(state),
      goBack,
      color_change,
      refreshCar,
      onConfigClick,
    };
  },
  components: {
    SameCar,
    CarList,
  },
};
</script>

<style lang="less" scoped>
.container {
  overflow-y: hidden;
  height: 100%;

  p {
    margin: 0;
  }

  .header {
    padding: 10px;
    box-sizing: border-box;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: linear-gradient(10deg, #eee, #fff, #eee);

    .img {
      width: 15px;
      height: auto;
    }

    p {
      font-size: 12px;
      color: black;
    }

    .strong {
      font-size: 18px;
      font-weight: 900;
      color: #000;
    }
  }

  .content {
    width: 100%;
    position: relative;
    background: linear-gradient(30deg, #ddd, #eee, #fff, #eee);

    .content_top {
      width: 100%;
      height: 100%;
      position: relative;

      .image {
        width: 100%;
        height: 100%;
        position: relative;
        min-height: 200px;
        overflow: hidden;

        .image_in {
          position: absolute;
          width: 100%;
          height: 100%;
          text-align: center;
          box-sizing: border-box;

          img {
            opacity: 1;
            width: auto;
            height: 100%;
            transition: all 0.5s;
          }
        }
      }

      .iconIndex {
        display: flex;
        justify-content: center;
        align-items: center;

        .radius {
          display: inline-block;
          position: relative;
          border-radius: 50%;
          bottom: 20px;
          width: 15px;
          height: 15px;
          margin: 0 10px;
          background: #def;
          text-align: center;
        }
      }

      .right {
        position: absolute;
        right: 10px;
        bottom: 100px;

        p {
          opacity: 0.5;
          font-size: 12px;
          line-height: 12px;
          margin: 8px auto;
          padding: 2px 5px;
          border-radius: 5px;
          //   background: #def;
          box-shadow: 5px 5px 5px #aaa;
        }
      }
    }

    .content_bottom {
      text-align: left;
      padding: 0 20px;
      box-sizing: border-box;

      span {
        display: inline-block;
        font-size: 12px;
        color: #aaa;
      }

      .left {
        display: inline-block;
        font-size: 16px;
        font-weight: 500;
        color: #000;
      }
    }
  }

  .footer {
    width: 100%;
    background: #fff;

    .lineCar {
      height: calc(100vh - 350px);
      overflow-y: scroll;
      width: 100%;
      padding: 0 10px;
      box-sizing: border-box;
    }

    .emtyp {
      height: calc(100vh - 350px);
      display: flex;
      justify-content: center;
      margin-top: 50px;
      //  align-items: center;
    }
  }
}
</style>